package com.example.demo.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;

public class SelectorServerTest3 {
    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector selector=Selector.open();

        ssc.register(selector, SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8082));
        while (true){
            selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey selectionKey=iterator.next();
                iterator.remove();
                if(selectionKey.isAcceptable()){
                    SocketChannel socketChannel = ssc.accept();
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ);
                    socketChannel.register(selector,SelectionKey.OP_WRITE);
//                    StringBuilder sb=new StringBuilder();
//                    for (int i=0;i<300000;i++){
//                        sb.append("a");
//                    }
//                    ByteBuffer byteBuffer = Charset.defaultCharset().encode(sb.toString());
//                    socketChannel.register(selector,SelectionKey.OP_WRITE,byteBuffer);
                    System.out.println("连接事件处理完毕");
                }else if(selectionKey.isReadable()){
                    System.out.println("开始读取数据");
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    channel.read(byteBuffer);
                    if(!byteBuffer.hasRemaining()){
                        System.out.println("读取到数据"+(char)byteBuffer.get());
                        byteBuffer.clear();
                    }
                }else if(selectionKey.isWritable()){
                    StringBuilder sb=new StringBuilder();
                    for (int i=0;i<300000;i++){
                        sb.append("a");
                    }
                    ByteBuffer byteBuffer = Charset.defaultCharset().encode(sb.toString());
//                    ByteBuffer byteBuffer=(ByteBuffer) selectionKey.attachment();
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    int write=channel.write(byteBuffer);
                    System.out.println("写入位置："+write);
                    if (!byteBuffer.hasRemaining()){
                        selectionKey.attach(null);
                        selectionKey.interestOps(selectionKey.interestOps()-SelectionKey.OP_WRITE);
                    }

                }
            }
        }
    }
}
